import moment from "moment";
import store from "../../store";
import crypto from "./crypto";
import axios from "axios";
import base from "../../public/base";
import { Locale } from "vant";
import { Toast } from "vant";
const MODE = import.meta.env.MODE;
// 引入英文语言包
import enUS from "vant/es/locale/lang/en-US";
import zhCN from "vant/es/locale/lang/zh-CN";

export function initLang() {
  let lang = localStorage.getItem("lang");
  if (lang == "en") {
    Locale.use("en-US", enUS);
  } else {
    Locale.use("zh-CN", zhCN);
  }
}

export function filterHTMLCode(html) {
  if (!html) return "";
  let str = html;
  str = str.replace(
    /<img /,
    `<img class="reviewImg" onclick="reviewImg(this)" style="width:100%"`
  );

  return str;
}

export function isIosDev() {
  let isIos = false;

  if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
    isIos = true;
  }
  if (/android/i.test(navigator.userAgent)) {
    console.log("Android"); //Android
    isIos = false;
  }
  return isIos;
}

export function encrypt(type, data) {
  //获取当前时间戳13位 + 3位字符
  var timestamp = exchangeDateTime(new Date(), 41); //密码
  timestamp = `${timestamp}${timestamp.split("").reverse().join("")}`;

  //加密密钥16位
  var encrypt_key = timestamp; //长度必须为16位
  //加密向量16位
  var iv = "ZZWBKJ_ZHIHUAWEI";

  if (type == "encrypt") {
    return crypto.encrypt(JSON.stringify(data), encrypt_key, iv);
  } else if (type == "decrypt") {
    console.log("decrypt", data, encrypt_key, iv);
    return crypto.decrypt(data, encrypt_key, iv);
  }
}

export function encryptPas(type, data, password) {
  if (password == "Tsg@050929(") {
    //获取当前时间戳13位 + 3位字符
    var timestamp = exchangeDateTime(new Date(), 41); //密码
    timestamp = `${timestamp}${timestamp.split("").reverse().join("")}`;

    //加密密钥16位
    var encrypt_key = timestamp; //长度必须为16位
    //加密向量16位
    var iv = "ZZWBKJ_ZHIHUAWEI";

    if (type == "encrypt") {
      return crypto.encrypt(JSON.stringify(data), encrypt_key, iv);
    } else if (type == "decrypt") {
      console.log("decrypt", data, encrypt_key, iv);
      return crypto.decrypt(data, encrypt_key, iv);
    }
  } else {
    alert("禁止使用！");
  }
}

export function useLanguage() {
  const UserInfo =
    sessionStorage.getItem("UserInfo") &&
    JSON.parse(sessionStorage.getItem("UserInfo"));
  let language = "zh";
  if (!UserInfo) {
    return language;
  }
  if (UserInfo?.language == 2) {
    language = "en";
  }
  return language;
}

export function toHourMinute(minutes) {
  //   return Math.floor(minutes / 60) + "小时" + (minutes % 60) + "分";
  // 也可以转换为json，以方便专外部使用属
  let times = { h: Math.floor(minutes / 60), m: minutes % 60 };
  times.h = times.h < 10 ? `0${times.h}` : times.h;
  times.m = times.m < 10 ? `0${times.m}` : times.m;
  return times;
}

export function toSecondsMinute(seconds) {
  let s = seconds % 60;
  let m = Math.floor(seconds / 60);
  //   return Math.floor(minutes / 60) + "小时" + (minutes % 60) + "分";
  // 也可以转换为json，以方便专外部使用属
  let times = { h: Math.floor(m / 60), m: m % 60, s: s };
  times.h = times.h < 10 ? `0${times.h}` : times.h;
  times.m = times.m < 10 ? `0${times.m}` : times.m;
  times.s = times.s < 10 ? `0${times.s}` : times.s;
  return times;
}

export const exchangeDateTime = (date, type = "") => {
  let lang = useLanguage();

  switch (type) {
    case 43:
      return moment(date).format("HH:mm:ss");
    case 42:
      return lang == "zh"
        ? moment(date).format("YYYY年MM月DD日")
        : moment(date).format("DD MMM YYYY");
    case 41:
      //20210415
      return moment(date).format("YYYYMMDD");
    case 40:
      return moment(date).format("MM-DD");
    case 39:
      //2021-04
      return moment(date).format("YYYY-MM");
    case 38:
      return lang == "zh"
        ? moment(date).format("MM月DD日")
        : moment(date).format("DD MMM");
    case 37:
      //17 May 2022 5:38 PM
      return moment(date).format("DD MMM YYYY h:mm A");
    case 36:
      //15-04-2021 5:24 PM
      return moment(date).format("DD-MM-YYYY H:mm A");
    case 35:
      //15/04/2021 5:24 PM
      return moment(date).format("DD/MM/YYYY H:mm A");
    case 34:
      //15/04/2021 17:24
      return moment(date).format("DD/MM/YYYY H:mm");
    // 03:33
    case 33:
      return moment(date).format("HH:mm");
    // isToday
    case 32:
      return moment().isSame(date, "day");
    case 31:
      /* Monday */
      return moment(date).format("dddd");
    case 30:
      //15-04-2021
      return moment(date).format("DD-MM-YYYY");
    case 29:
      return moment().format("DD MMM YYYY, hh:mma");
    case 28:
      return moment(date).valueOf();
    case 27:
      // 3 next year
      return moment(date).add(3, "year");
    case 26:
      return moment(moment(date).format("YYYY-MM-DD")).valueOf();
    case 25:
      // next day
      return moment(date).add(1, "day");
    case 24:
      /* Monday 1 January 2020 */
      return moment(date).format("dd MMM DD YYYY");
    case 23:
      //2021-04-15 03:24:12
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    case 22:
      /* 1 Jan 2020,18:00 */
      return moment(date).format("DD MMM YYYY,HH:mm");
    case 20:
      /* 1 Jan 2020,Fri */
      return moment(date).format("DD MMM YYYY,ddd");
    case 18:
      /* 1 Jan 2020 */
      return moment(date).format("DD MMM YYYY");
    case 17:
      /* 1 January 2020,Fri */
      return moment(date).format("DD MMMM YYYY,ddd");
    case 16:
      /* 毫秒 */
      return moment(date).valueOf();
    case 15:
      /* January 2020 */
      return moment(date).format("MMMM YYYY");
    case 14:
      //2021-04-15 17:24:12
      return moment(date).format("YYYY-MM-DD H:mm:ss");
    case 13:
      /* 05 February 2021, 00:00 */
      return moment(date).format("DD MMMM YYYY, HH:mm");
    case 12:
      /* Mon Apr 26 2021 12:00:00 GMT+0800 (中国标准时间) */
      return moment(date).toDate();
    case 11:
      /* Monday, 1 January 2020 */
      return moment(date).format("dddd, DD MMMM YYYY");
    case 10:
      // 1 / 2 / 3 / 4 / 5 / 6 / 7
      return moment(date).day();
    case 9:
      // 15 April 2021
      return moment(date).format("DD MMMM YYYY");
    case 8:
      // 17:22
      return moment(date).format("HH:mm");
    case 7:
      // 15 Apr 17:23 PM
      return moment(date).format("DD MMM H:mm A");
    case 6:
      // 17:23 pm
      return moment(date).format("H:mm a");
    case 5:
      //15 Apr
      return moment(date).format("DD MMM");
    case 4:
      //Thursday
      return moment(date).format("dddd");
    case 3:
      //2021-04-15 17:24
      return moment(date).format("YYYY-MM-DD H:mm");
    case 2:
      //2021-04-15
      return moment(date).format("YYYY-MM-DD");
    case 1:
      //17:25
      return moment(date).format("H:mm");
    default:
      //15/04/2021
      return moment(date).format("DD/MM/YYYY");
  }
};
export function getWeek(date) {
  let lang = store?.state?.lang?.lang || "zh";
  let getTime = moment(date);
  let currentTime = moment(new Date());

  if (getTime.date() == currentTime.date()) {
    return lang == "zh" ? "今天" : "Today";
  } else if (currentTime.date() + 1 == getTime.date()) {
    return lang == "zh" ? "明天" : "Tomorrow";
  } else if (currentTime.date() + 2 == getTime.date()) {
    return lang == "zh" ? "后天" : "After tomorrow";
  }

  // 参数时间戳
  let week = moment(date).day();
  console.log(week);
  switch (week) {
    case 1:
      return lang == "zh" ? "周一" : "Monday";
    case 2:
      return lang == "zh" ? "周二" : "Tuesday";
    case 3:
      return lang == "zh" ? "周三" : "Wednesday";
    case 4:
      return lang == "zh" ? "周四" : "Thursday";
    case 5:
      return lang == "zh" ? "周五" : "Friday";
    case 6:
      return lang == "zh" ? "周六" : "Saturday";
    case 0:
      return lang == "zh" ? "周日" : "Sunday";
  }
}

export function getWeekList(list = [1, 2, 3, 4, 5, 6, 0], abbreviation = 1) {
  let lang = store?.state?.lang?.lang || "zh";

  return list.map((item, index) => {
    switch (item) {
      case 1:
        return lang == "zh" ? "周一" : abbreviation ? "Mon." : "Monday";
      case 2:
        return lang == "zh" ? "周二" : abbreviation ? "Tue." : "Tuesday";
      case 3:
        return lang == "zh" ? "周三" : abbreviation ? "Wed." : "Wednesday";
      case 4:
        return lang == "zh" ? "周四" : abbreviation ? "Thur." : "Thursday";
      case 5:
        return lang == "zh" ? "周五" : abbreviation ? "Fri." : "Friday";
      case 6:
        return lang == "zh" ? "周六" : abbreviation ? "Sat." : "Saturday";
      case 0:
        return lang == "zh" ? "周日" : abbreviation ? "Sun." : "Sunday";
    }
    return item;
  });
}



export function getUrlKey(key) {
  let reg = new RegExp("[?&]" + key + "(=([^&#]*)|&|#|$)");
  return reg.exec(window.location.href)[2];
}
export function getUrlParam(name) {
  //封装方法

  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象

  var r = window.location.href.substr(1).match(reg); //匹配目标参数

  if (r != null) return unescape(r[2]);

  return null; //返回参数值
}

export function filterTreeEn(list) {
  let lang = useLanguage();
  if (!list?.length) {
    return [];
  }
  return list.map((item, index) => {
    if (lang == "en") {
      item.name = item.enname || item.name;
    }
    if (item.children) {
      filterTreeEn(item.children);
    }
    return item;
  });
}

export function timeValidation(target, current = new Date()) {
  let t = new Date(target);
  if (t < current) {
    return false;
  }
  return true;
}

export function timeMoment(target, current) {
  let currentTime = moment(new Date());
  let selectTime = (current && moment(current)) || moment(new Date());

  if (selectTime.date() == currentTime.date()) {
    let cH = currentTime.hour();
    let cM = currentTime.minute();
    if (moment.duration(target) < moment.duration(`${cH}:${cM}`)) {
      return true;
    }
    return false;
  } else {
    return false;
  }
}

export function timeEndMoment(target, current) {
  console.log("结束时间", current);
  let currentTime = moment(current || new Date());

  let cH = currentTime.hour();
  let cM = currentTime.minute();
  if (moment.duration(target) < moment.duration(`${cH}:${cM}`)) {
    return true;
  }
  return false;
}

export function timeStartMoment(target, current) {
  console.log("开始时间", current);

  let currentTime = moment(current || new Date());

  let cH = currentTime.hour();
  let cM = currentTime.minute();
  let cS = currentTime.seconds();

  if (moment.duration(target) < moment.duration(`${cH}:${cM}:${cS}`)) {
    return false;
  } else {
    let remainder =
      moment.duration(target) - moment.duration(`${cH}:${cM}:${cS}`);
    return remainder;
  }
}

export function uploadFile(file) {
  let token = sessionStorage.getItem("token") || "";

  return new Promise((resolve, reject) => {
    var forms = new FormData();
    var configs = {
      headers: { "Content-Type": "multipart/form-data" },
    };
    configs.headers["authorization"] = `bearer${token}`;
    forms.append("file", file);
    Toast.loading({ duration: 0, overlay: true });
    axios
      .post(
        `${MODE == "production" ? location.origin : "/api"}/api/Upload/upload`,
        forms,
        configs
      )
      .then((res) => {
        resolve(res.data);
        Toast.clear();
      })
      .catch(() => {
        reject();
        Toast.clear();
      });
  });
}

export function futureDays() {
  var dd = new Date();
  var arr = [];
  for(var i = 0; i < 7; i++){
    dd.setDate(dd.getDate() + 1);
    var mon = dd.getMonth() + 1
    var day = dd.getDate()
    arr.push(dd.getFullYear() + '-' + (mon < 10 ? ('0' + mon) : mon) + "-" +(day < 10 ? ('0' + day) : day))
  }
	return arr
}

//根据日期获取周几
export function geThisWeek(dateString) {
	var dateArray = dateString.split("-");
	var date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
	return "周" + "日一二三四五六".charAt(date.getDay());
};

export function getThisWeekData() {
  //获得本周周一~周日的年月日
  var thisweek = {};
  var date = new Date();
  // 本周一的日期
  date.setDate(date.getDate() - date.getDay() + 1);
  thisweek.start_day =
    date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();

  // 本周日的日期
  date.setDate(date.getDate() + 6);
  thisweek.end_day =
    date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
  console.log("设备", isIosDev(), thisweek);
  if (isIosDev()) {
    thisweek.start_day = thisweek.start_day.replace(/-/g, "/");
    thisweek.end_day = thisweek.start_day.replace(/-/g, "/");
  }
  return thisweek;
}

export function getLastWeekData() {
  //获得上周周一~周日的年月日
  var lastweek = {};
  var date = new Date();
  // 上周一的日期
  date.setDate(date.getDate() - 7 - date.getDay() + 1);
  lastweek.start_day =
    date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();

  // 上周日的日期
  date.setDate(date.getDate() + 6);
  lastweek.end_day =
    date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
  if (isIosDev()) {
    lastweek.start_day = lastweek.start_day.replace(/-/g, "/");
    lastweek.end_day = lastweek.end_day.replace(/-/g, "/");
  }
  return lastweek;
}

// 中国标准时间format yyyy-mm-dd
const format = (time) => {
  let ymd = "";
  let mouth =
    time.getMonth() + 1 >= 10
      ? time.getMonth() + 1
      : "0" + (time.getMonth() + 1);
  let day = time.getDate() >= 10 ? time.getDate() : "0" + time.getDate();
  ymd += time.getFullYear() + "-"; // 获取年份。
  ymd += mouth + "-"; // 获取月份。
  ymd += day; // 获取日。
  return ymd; // 返回日期。
};

export const getAllDate = (start, end) => {
  let dateArr = [];
  let startArr = start.split("-");
  let endArr = end.split("-");
  let db = new Date();
  db.setUTCFullYear(startArr[0], startArr[1] - 1, startArr[2]);
  let de = new Date();
  de.setUTCFullYear(endArr[0], endArr[1] - 1, endArr[2]);
  let unixDb = db.getTime();
  let unixDe = de.getTime();
  let stamp;
  const oneDay = 24 * 60 * 60 * 1000;
  for (stamp = unixDb; stamp <= unixDe; ) {
    dateArr.push(format(new Date(parseInt(stamp))));
    stamp = stamp + oneDay;
  }
  return dateArr;
};

export const isVoid = (value) =>
  value === undefined || value === null || value === "" || value?.length == 0;

export const cleanObject = (object) => {
  const result = { ...object };
  Object.keys(result).forEach((key) => {
    const value = result[key];
    if (isVoid(value)) {
      delete result[key];
    }
  });

  return result;
};

export const getDates = (startDate, endDate) => {
  var dates = [];
  var currentDate = new Date(startDate);
  var endDateObj = new Date(endDate);

  while (currentDate <= endDateObj) {
    dates.push(currentDate.toISOString().slice(0, 10));
    currentDate.setDate(currentDate.getDate() + 1);
  }

  return dates;
};

export const getFileSizeInMB = (file) => {
  const fileSizeInBytes = file.size;
  const fileSizeInMB = fileSizeInBytes / (1024 * 1024); // Convert bytes to MB
  const formattedSize = fileSizeInMB.toFixed(2); // Limit decimal places to 2
  return formattedSize;
};

export const getFileSizeInKB = (file) => {
  const fileSizeInBytes = file.size;
  const fileSizeInKB = fileSizeInBytes / 1024; // Convert bytes to KB
  const formattedSize = fileSizeInKB.toFixed(2); // Limit decimal places to 2
  return formattedSize;
};

export const getFileType = (type) => {
  const fileExtension = type;
  let fileType = "";
  // 判断文件类型
  if (
    fileExtension === "jpg" ||
    fileExtension === "jpeg" ||
    fileExtension === "png" ||
    fileExtension === "gif"
  ) {
    fileType = "IMG";
  } else if (fileExtension === "mp3" || fileExtension === "wav") {
    fileType = "AUDIO";
  } else if (
    fileExtension === "mp4" ||
    fileExtension === "avi" ||
    fileExtension === "mov"
  ) {
    fileType = "VIDEO";
  } else if (fileExtension === "pdf") {
    fileType = "PDF";
  } else if (fileExtension === "doc" || fileExtension === "docx") {
    fileType = "WORD";
  } else if (fileExtension === "xls" || fileExtension === "xlsx") {
    fileType = "EXCEL";
  }

  return fileType;
};

export const getFileExtension = (filename) => {
  const fileExtension = filename.slice(
    ((filename.lastIndexOf(".") - 1) >>> 0) + 2
  );
  let fileType = "";
  // 判断文件类型
  if (
    fileExtension === "jpg" ||
    fileExtension === "jpeg" ||
    fileExtension === "png" ||
    fileExtension === "gif"
  ) {
    fileType = "IMG";
  } else if (fileExtension === "mp3" || fileExtension === "wav") {
    fileType = "AUDIO";
  } else if (
    fileExtension === "mp4" ||
    fileExtension === "avi" ||
    fileExtension === "mov"
  ) {
    fileType = "VIDEO";
  } else if (fileExtension === "pdf") {
    fileType = "PDF";
  } else if (fileExtension === "doc" || fileExtension === "docx") {
    fileType = "WORD";
  } else if (fileExtension === "xls" || fileExtension === "xlsx") {
    fileType = "EXCEL";
  }

  return fileType;
};

export const nextDate = (type) => {
  // type : days | weeks | months
  var date = moment().add(1, type);
  if (type) {
    date = moment().add(1, type);
  } else {
    date = moment();
  }

  return date.format("YYYY-MM-DD");
};

export function jsonToUrlParams(jsonObj) {
  return Object.keys(jsonObj)
    .map(
      (key) => `${encodeURIComponent(key)}=${encodeURIComponent(jsonObj[key])}`
    )
    .join("&");
}
